import React, { useState, useEffect } from 'react';
import { save_data, Btn, for_obj, Ret, Title, useHigh, GridTable, useCmd, WaitUmd, MainView, obj_str, PanelTitle, d_sort, obj_int, is_empty, loc } from 'sui';

const Census = ({ data, title, hreturn, mod, name }) => {
    const [row, setRow] = useState();
    const [high] = useHigh(220, 100);
    const umd = useCmd();

    useEffect(() => {
        if (is_empty(data)) {
            setRow(null);
            return;
        }

        const val = {};

        data.forEach(d => {
            const tech = obj_str(d, mod);
            if (val[tech]) {
                val[tech].push(d);
            } else {
                val[tech] = [d];
            }
        });

        const ret = [];

        for_obj(val, (k, v) => {
            let pnum = 0;
            let num = 0;
            let dnum = 0;

            v.forEach(d => {
                pnum += obj_int(d, "pnum");
                num += obj_int(d, "num");
                dnum += obj_int(d, "dnum");
            });

            ret.push({
                tech: k,
                pnum: pnum,
                dnum: dnum,
                num: num,
            });
        });

        d_sort(ret, "tech");

        ret.forEach((d, i) => d["index"] = i + 1);

        setRow(ret);
    }, [data, mod]);

    const col = [
        {name: loc("l_193"), key: 'index', width: 120},
        {name: name, key: 'tech', width: 120},
        {name: loc("l_455"), key: 'pnum', width: 120},
        {name: loc("l_473"), key: 'num', width: 120},
        {name: loc("l_524"), key: 'dnum', width: 120},
    ];

    const hExport = () => {
        save_data(row, col, title, umd);
    };

    const Right = () => (
        <div className="inline-flex">
            <Btn hcmd={hExport} className="mr-4">{loc("l_298")}</Btn>
            <Ret hcmd={hreturn}/>
        </div>
    );

    return (
        <MainView>
            <PanelTitle left={<Title mod={loc("l_454")} sub={title}/>} right={<Right/>} cl="gray"/>
            <GridTable col={col} row={row} high={high}/>
            <WaitUmd umd={umd}/>
        </MainView>
    );
};

export {Census};
